package com.business_clean.app.weight;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.business_clean.R;
import com.business_clean.app.uitl.GlideUtil;

public class CustomAvatarView extends LinearLayout {

    private ImageView avatarImage;
    private TextView avatarText;

    public CustomAvatarView(Context context) {
        super(context);
        init(context);
    }

    public CustomAvatarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CustomAvatarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.custom_avatar, this, true);
        avatarImage = findViewById(R.id.avatarImage);
        avatarText = findViewById(R.id.avatarText);
    }

    public TextView getAvatarText() {
        return avatarText;
    }

    public ImageView getAvatarImage() {
        return avatarImage;
    }

    public void setAvatar(String avatarUrl, String name) {
        if (avatarUrl != null && !avatarUrl.isEmpty()) {
            // 如果有头像地址，则显示头像图片
            avatarImage.setVisibility(View.VISIBLE);
            // TODO: 使用头像地址加载头像图片
            GlideUtil.loadPicRound(avatarImage.getContext(), avatarUrl, avatarImage, 4);
        } else {
            String displayName = "";
            avatarImage.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(name)) {
                // 如果没有头像地址，则显示文字头像
                displayName = getDisplayName(name);
            } else {
                displayName = getDisplayName("--");
            }
            avatarText.setText(displayName);
            setVisibility(View.VISIBLE);
        }
    }

    private String getDisplayName(String name) {
        if (name.length() <= 2) {
            return name;
        } else {
            return name.substring(name.length() - 2);
        }
    }
}
